<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/6/16
 * Time: 21:00
 */
namespace Pay\Controller;

use Common\Common\Api\Order;
use Common\Common\Api\Ordermember;
use Common\Common\Api\Redis\Channel;
use Common\Common\Api\Redis\Product;

/**
 * Class ManyiController
 * @package Pay\Controller
 * 信誉付2
 */
class Xinyufu2Controller extends PayController{
    protected $config;
    protected $class;
    public function __construct(){
        parent::__construct();
        $classes = explode("\\",__CLASS__);
        $class = end($classes);
        $this->class = substr($class, 0, stripos($class, "Controller"));
    }

    public function pay($array){
        $this->config = Channel::getInstance()->getById($array['channel']);

        if(!$this->config){
            $this->showmessage('通道错误!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $product = Product::getInstance()->getById(I("request.pay_bankcode",0,"intval"));

        if(!$product){
            $this->showmessage('未找到支付产品!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $parameter = array(
            'code' => $this->config['code'], // 通道名称
            'title' => $this->config['title'],
            'exchange' => 1, // 金额比例
            'gateway' => $this->config['gateway'],
            'orderid' => createOrderId(),
            'out_trade_id' => I("request.pay_orderid"),
            'body' => 'pay',
            'channel'=>$array
        );

        $isMobile = isMobile();
        $return = $this->orderadd( $parameter );


        $data = array();
        $data['V'] = 'V4.0';
        $data['UserNo'] = $this->config['mch_id'];
        $data['ordNo'] = $return['orderid'];
        $data['ordTime'] = date("YmdHis",time());
        $data['amount'] = intval($return['amount'] * 100);

        switch($this->config['paytype']){
            case 3:
            case 4:
            case 17:
            case 18:
               $data['pid'] = 'apzf';
                break;
            case 1:
            case 2:
                $data['pid'] = 'wxzf';
                break;
            case 13:
                $data['pid'] = 'kj';
                break;
            case 8:
            case 10:
                $data['pid'] = 'qqzf';
                break;
            default:
                $this->showmessage('暂不支持此方式!',['code'=>C("THIRDCODES.".$this->class)]);
        }
        $data['notifyUrl'] = $return['notifyurl'];
        $data['frontUrl'] = $return['callbackurl'];
        $data['remark'] = '18123663214';
        $data['ip'] = getIP();


        $str = "";
        foreach($data as $k=>$v){
            $str .= $v."|";
        }
        $str .= $this->config['signkey'];
        $data['sign'] = strtoupper(md5($str));

        $res = curl($this->config['gateway'], httpstr($data));

        /*echo '<pre/>';
        print_r($data);
        echo "网关地址：" . $this->config['gateway'] ."<br/><br/>";
        echo $res . '<br/>'; exit;*/
		
		//file_put_contents("a.txt", $res);

        if(!$res){
            $this->showmessage('未获取到返回数据!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $res = json_decode($res, true);

        $code = $res['Payurl'];
        if(!$code){
            if($res['resMsg']){
                $this->showmessage($res['resMsg'],['code'=>C("THIRDCODES.".$this->class)]);
            }
            $this->showmessage('获取支付链接失败!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        if($isMobile && in_array($this->config['paytype'],[3,4,17,18])){
            header("Location: {$code}"); exit;
        }

        switch($this->config['paytype']){
            case 3:
            case 4:
            case 17:
            case 18:
                if($isMobile){
                    header("Location: {$code}"); exit;
                }
                break;
            case 13:
                header("Location: {$code}"); exit;
                break;
            case 8:
            case 10:
		case 1:
		case 2:
            
                break;
            default:
                $this->showmessage('暂不支持此方式!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $paytype = transArr( C("PAYTYPES"), "id");

        //$this->assign("code_url", $code);
        $this->assign("title", $paytype[$this->config['paytype']]);
        $this->assign("return", $return);
        $this->assign("imgurl", C("website.DOMAIN")."/Pay_Qrcode_getCode?type=2&data=" . base64_encode($code));

        switch($this->config['paytype']){
            //支付宝扫码
            case 3:
            case 4:
            case 17:
            case 18:
                $this->display("WeiXin/alipay");
                break;
            case 8:
            case 10:
                if($isMobile){
                    header("Location: {$code}");
                }else{
                    $this->display("WeiXin/qq");
                }
                break;
            case 1:
            case 2:
                if($isMobile){
                    header("Location: {$code}");
                }else{
                    $this->display("WeiXin/weixin");
                }
                break;
            default:
                $this->display("WeiXin/Pay");
        }
    }

    private function getSign($data){
        $r = [];
        foreach($data as $k=>$v){
            if($k === 'sign' || $v === ''){
                continue;
            }

            $r[$k] = $v;
        }

        ksort($r);

        $r['key'] = $this->config['signkey'];

        $str = '';
        foreach($r as $k=>$v){
            $str .= $v;
        }

        return hash("sha256", $str);
    }

    private function zhifubao($return){
        $data = array();
        $data['V'] = 'V4.0';
        $data['UserNo'] = $this->config['mch_id'];
        $data['ordNo'] = $return['orderid'];
        $data['ordTime'] = date("YmdHis",time());
        $data['amount'] = intval($return['amount'] * 100);
        $data['pid'] = 'apzf';
        $data['notifyUrl'] = $return['notifyurl'];
        $data['frontUrl'] = $return['callbackurl'];
        $data['remark'] = '18123663214';
        $data['ip'] = getIP();


        $str = "";
        foreach($data as $k=>$v){
            $str .= $v."|";
        }
        $str .= $this->config['signkey'];
        $data['sign'] = strtoupper(md5($str));

        $res = curl($this->config['gateway'], httpstr($data));

        if(!$res){
            $this->showmessage('未获取到返回数据!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $res = json_decode($res, true);

        $code = $res['Payurl'];
        if(!$code){
            if($res['resMsg']){
                $this->showmessage($res['resMsg'],['code'=>C("THIRDCODES.".$this->class)]);
            }
            $this->showmessage('获取支付链接失败!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        return $code;
    }

    //通知
    public function notifyurl(){
        //file_put_contents("a.txt","post: ".var_export($_POST,true)."\r\n\r\n");
        //file_put_contents("a.txt","get: ".var_export($_GET,true)."\r\n\r\n", FILE_APPEND);
        //file_put_contents("a.txt", "input: ".file_get_contents('php://input')."\r\n\r\n", FILE_APPEND);
        //file_put_contents("a.txt", "ip: ".getIP()."\r\n\r\n", FILE_APPEND);
        //file_put_contents("a.txt", "time: ".date("Y-m-d H:i:s",time())."\r\n\r\n", FILE_APPEND);

        $p = $origin = I("post.");

        /*$p = array (
            'V' => 'V4.0',
            'UserNo' => '1000824',
            'ordNo' => '2018122814081479369',
            'amount' => '1000',
            'status' => '1001',
            'reqTime' => '20181228140815',
            'reqNo' => 'AA812281408150009KX',
            'remark' => '',
            'sign' => '21033B8611C269164C0622C4B5C1C29A',
        );*/

        if(!$p || empty($p)){
            exit("wrong");
        }

        //获取订单信息
        $orderid = $p['ordNo'];
        $find = $this->checkOrderNotify($orderid);
        if(!$find){
            echo 'order_not_found'; exit;
        }

        //保存回调数据
        M("Order")->where(array("pay_orderid"=>$orderid))->save(array(

            "pay_orderid_rd"=> htmlspecialchars($p['reqNo'])
        ));

        //获取渠道信息
        $this->config = M("Channel")->where(array('code'=>$this->class))->find();


        //echo '<pre/>'; print_r($p);

        $sign = $p['sign'];
        unset($p['sign']);

        $str = "";
        foreach($p as $k=>$v){
            if($v === ''){
                continue;
            }

            $str .= $v."|";
        }
        $str .= $this->config['signkey'];
        $sign2 = strtoupper(md5($str));

        //echo "签名字符串：" . $str . "<br/><br/>";
        //echo 'sign: '.$sign .'<br/>';
        //echo 'sign2:'. $sign2 .'<br/>'; exit;

        if($sign !== $sign2){
            exit("sign_wrong");
        }

        if($p['status'] !== '1001'){
            exit("pay_fail");
        }

        $this->async($find['pay_orderid'],'OK');
    }

    public function callBackUrl(){

        echo '处理成功'; exit;
    }
}
